var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    checkin_list: [],
    lp_list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    if (e.id) {
      that.setData({
        id:e.id
      })
    }
    // app.socket.on('lp', function (data) {
    //   if (data.type == 'checkin' && data.user_id == 'u' +app.globalData.user_id) {
    //     plugin.textToSpeech({
    //       lang: "zh_CN",
    //       tts: true,
    //       content: data.plate + '已签到',
    //       success: function (res) {
    //         const innerAudioContext = wx.createInnerAudioContext()
    //         innerAudioContext.autoplay = true
    //         innerAudioContext.src = res.filename;
    //         innerAudioContext.onPlay(() => {})
    //       },
    //       fail: function (res) {
    //         console.log("fail tts", res)
    //       }
    //     })
    //     wx.showToast({
    //       title: data.plate + '已签到',
    //       icon: "success",
    //       duration: 3000,
    //       success: function () {
    //         setTimeout(function () {
    //           that.loadList();
    //         }, 3000);
    //       }
    //     });
    //   }
    // });
    this.loadList();
    this.getLpState();
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  loadList: function () {
    var that = this;
    util.getData("/atapi/loadingplatform/loadingplatform/lpById", {
      'id': that.data.id
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        that.setData(res.data.data);
        that.setData({
          lp_list: res.data.lp_list,
          checkin_list: res.data.checkin_list
        })
      }
    });
  },
  getLpState: function () {
    var that = this;
    util.getData("/atapi/loadingplatform/loadingplatform/getLpState", {
      'id': that.data.id
    }, function (res, error) {
      console.log(res); console.log(error)
      var total_vehicle = 0,cy_vehicle = 0,booking_vehicle = 0,queue_vehicle = 0,leave_vehicle = 0;
      if (res.data.success) {
        var data = res.data.data;
        for(var i=0;i<data.length;i++){
          total_vehicle ++;
           if(data[i].containeryard && data[i].cy_get==1){
            cy_vehicle ++;
           }
           if(data[i].checkin_time){
            booking_vehicle ++;
            data[i].checkin_time = moment(data[i].checkin_time).format('YYYY-MM-DD HH:mm:ss')
           }
           if(data[i].queue_time){
            queue_vehicle ++;
            data[i].queue_time = moment(data[i].queue_time).format('YYYY-MM-DD HH:mm:ss')
           }
           if(data[i].is_load == 1){
            leave_vehicle ++;
           }
           if(!data[i].iot_box){
            data[i].iot_box = 'WX'+data[i].vehicle;
           }
        }
        that.setData({
          vehicleData:data
        })
        //获取车辆位置
        for(var i=0;i<data.length;i++){
          util.getData("/atapi/loadingplatform/loadingplatform/getVehicleAddress", {
            'iot_box':data[i].iot_box,
            'coord':(data[i].containeryard && data[i].cy_get != 1)?data[i].cy_coord:data[i].wh_coord
          }, function (res, error) {
            console.log(res); console.log(error)
            var vehicleData = that.data.vehicleData;
            for(var j=0;j<vehicleData.length;j++){
               if(vehicleData[j].iot_box == res.data.iot_box){
                vehicleData[j].address = res.data.address;
                 vehicleData[j].distance = res.data.distance;
                 vehicleData[j].duration = res.data.duration;
                 vehicleData[j].ps_time = res.data.ps_time;
               }
            }
            that.setData({
              vehicleData:vehicleData
            })
          });
        }
      }else{
        that.setData({
          vehicleData:[]
        })
      }
      that.setData({
        total_vehicle:total_vehicle,
        cy_vehicle:cy_vehicle,
        booking_vehicle:booking_vehicle,
        queue_vehicle:queue_vehicle,
        leave_vehicle:leave_vehicle
      })
    });
  },
  backToList: function () {
    wx.redirectTo({
      url: '/pages/enterprise/shop'
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  refresh: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/loadingplatform/loading_platform_detail?id='+this.data.id
    })
  },
  changeManage: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/users_selected?users=' + e.currentTarget.dataset.manager + '&usersName=' + e.currentTarget.dataset.manager_name
    })
  },
  timeChange(e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  showModal(e) {
    var that = this;
    var lpnumber = e.currentTarget.dataset.lpnumber;
    that.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.name,
      modalType: e.currentTarget.dataset.type,
      currentLpNumber: lpnumber
    })
    if (e.currentTarget.dataset.type == 'queuePlan') {
      that.loadCheckinByLP();
    };
    if (e.currentTarget.dataset.type == 'queueList') {
      var checkin_list = that.data.checkin_list, checkin_list_queue = [];
      for (var i = 0; i < checkin_list.length;i++){
        if (checkin_list[i].lp_number == lpnumber){
          checkin_list_queue.push(checkin_list[i]);
        }
      }
      that.setData({
        checkin_list_queue: checkin_list_queue
      })
    };
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  vehicleSearch: function () {
    this.loadCheckinByLP()
  },
  loadCheckinByLP: function () {
    var that = this;
    util.getData("/atapi/loadingplatform/loadingplatform/checkinOfLpNumber", {
      'lp': that.data.id,
      'searchVal': that.data.vehicleSearchVal
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        that.setData({
          checkin_list_noqueue: res.data.data
        })
      }else{
        that.setData({
          checkin_list_noqueue: []
        })
      }
    });
  },
  selectVehicle: function (e) {
    var that = this;
    util.postData("/atapi/loadingplatform/loadingplatform/setVehicleIntoQueue", {
      'id': e.currentTarget.dataset.id,
      'lp_number': that.data.currentLpNumber
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: "已加入队列",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.loadList();
              that.setData({
                modalName: ''
              })
            }, 3000);
          }
        });

      } else {
        wx.showToast({
          title: "加入队列失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  noticeVehicleAtLP: function (e) {
    var that = this;
    util.postData("/atapi/loadingplatform/loadingplatform/noticeVehicleAtLP", {
      'lp': that.data.id,
      'lp_number': e.currentTarget.dataset.lpnumber
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: "已通知车辆",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.loadList();
            }, 3000);
          }
        });

      } else {
        wx.showToast({
          title: "通知车辆失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  moreMenu: function (e) {
    var that = this;
    var lp = e.currentTarget.dataset.lp;
    var lp_number = e.currentTarget.dataset.lp_number;
    var vehicle = e.currentTarget.dataset.vehicle;
    var checkin_list = that.data.checkin_list;
    var checkinId = '';
    for (var i = 0; i < checkin_list.length;i++){
      if (checkin_list[i].vehicle == vehicle){
        checkinId = checkin_list[i].ID;
      }
    }
    wx.showActionSheet({
      itemList: ['车辆已靠台', '车辆已离台'],
      success(res) {
        //车辆已靠台
        if(res.tapIndex == 0){
          wx.showLoading({
            title: '提交中...'
          });
          util.postData("/atapi/loadingplatform/loadingplatform/dockToPlat", {
            CO_ID: app.globalData.CO_ID,
            lp: lp,
            lp_number: lp_number
          }, function (res, error) {
            console.log(res);
            console.log(error)
            if (res.data.success) {
              wx.showToast({
                title: res.data.data,
                icon: 'success',
                duration: 2000,
                mask: true,
                success: function () {
                  //获取记录
                  setTimeout(function () {
                    that.loadList();
                  }, 2000)
                }
              })
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 2000
              })
            }
            wx.hideLoading();
          });
        }
        //车辆已离台
        if (res.tapIndex == 1) {
          wx.showLoading({
            title: '提交中...'
          });
          util.postData("/atapi/loadingplatform/loadingplatform/leavePlat", {
            CO_ID: app.globalData.CO_ID,
            lp: lp,
            lp_number: lp_number,
            checkinId: checkinId
          }, function (res, error) {
            console.log(res);
            console.log(error)
            if (res.data.success) {
              wx.showToast({
                title: res.data.data,
                icon: 'success',
                duration: 2000,
                mask: true,
                success: function () {
                  //获取记录
                  setTimeout(function () {
                    that.loadList();
                  }, 2000)
                }
              })
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 2000
              })
            }
            wx.hideLoading();
          });
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  submitLoadingplatform: function () {
    var that = this;
    if (!that.data.warehouseId) {
      wx.showToast({
        title: "请选择项目",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (!that.data.manager) {
      wx.showToast({
        title: "请选择管理员",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(that.data.lp_number) == true || that.data.lp_number <= 0) {
      wx.showToast({
        title: "装卸口数量有误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    util.postData("/atapi/loadingplatform/loadingplatform/new", {
      'CO_ID': app.globalData.CO_ID,
      'warehouseId': that.data.warehouseId,
      'warehouse': that.data.warehouse,
      'work_time_start': that.data.work_time_start,
      'work_time_end': that.data.work_time_end,
      'manager': that.data.manager,
      'manager_name': that.data.manager_name,
      'lp_number': that.data.lp_number
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        that.setData({
          modalName: null
        })
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/loadingplatform/loading_platform'
              })
            }, 3000);
          }
        });

      } else {
        wx.showToast({
          title: "提交失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          });
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {
          }
        });
      }
    });
    wx.getStorage({
      key: 'manager',
      success: function (res) {
        if (res.data) {
          that.setData({
            manager: res.data.manager,
            manager_name: res.data.manager_name
          });
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'manager',
          success: function (res) {
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})